package com.jy.api.domain;

import com.jy.api.signUpReq.member.MemberSignUpReq;
import com.jy.api.util.MyDateUtils;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;

import javax.persistence.*;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by hanxi on 2017/7/8.
 * 会员表
 */
@Entity
@Data
@NoArgsConstructor
public class Member {
    @Id
    @Column(length = 50)
    private String id;
    private String code;
    private String name;
    /**
     * 平台余额
     */
    private double amount = 0;
    /**
     * 加入平台时间
     */
    @Temporal(TemporalType.TIMESTAMP)
    private Date enrollmentTime = new Date();

    /**
     * 平台积分
     */
    private long points = 0;
    @Column(insertable = false, updatable = false)
    @Temporal(TemporalType.TIMESTAMP)
    private Date addTime;
    @Column(insertable = false, updatable = false)
    @Temporal(TemporalType.TIMESTAMP)
    private Date updateTime;
    private boolean enabled = true;
    /**
     * 微信open id
     */
    private String openId;
    private String mobile;

    /**
     * 头像
     */
    private String headImgUrl;

    /**
     * 生日
     */
    @Temporal(TemporalType.TIMESTAMP)
    private Date birthday;

    @OneToMany
    @JoinColumn(name = "member_id")
    private Set<MemberAccount> accounts = new HashSet<>();

    public Member(String id, String name, String openId) {
        this.id = id;
        this.name = name;
        this.openId = openId;
    }


    /**
     * 校验会员是否已成为店铺会员
     *
     * @return false没有关联关系 true 有
     */
    public Boolean checkStore(String storeId) {
        Boolean check = false;
        for (MemberAccount memberAccount : accounts) {
            if (StringUtils.equals(storeId, memberAccount.getStoreId())) {
                check = true;
                break;
            }
        }
        return check;
    }

    /**
     * 修改会员信息
     *
     * @param memberSignUpReq
     */
    public void updateMemberInfo(MemberSignUpReq memberSignUpReq) {
        name = memberSignUpReq.getName();
        mobile = memberSignUpReq.getMobile();
        headImgUrl = memberSignUpReq.getHeadImgUrl();
        if (StringUtils.isNotBlank(memberSignUpReq.getBirthday())) {
            birthday = MyDateUtils.getDateFormatDd(memberSignUpReq.getBirthday(), "yyyy-MM-dd");
        }


    }

    /**
     * 获取对应店铺账号信息
     *
     * @param storeId
     * @return
     */
    public MemberAccount getStoreAccount(String storeId) {
        MemberAccount memberAccount = null;
        for (MemberAccount account : accounts) {
            if (StringUtils.equals(account.getStoreId(), storeId)) {
                memberAccount = account;
                break;
            }
        }
        return memberAccount;
    }

    public void addPointByAmount(double amount, double discount) {
        this.points += (int) amount;
        this.amount += amount + discount;
    }

}
